/**
 * 用户认证相关API
 * 统一管理登录、注册、token验证等认证相关接口
 */

import { post, get } from '@/utils/request';
import storage from '@/utils/storage';

/**
 * 统一登录接口
 * @param {string} type - 登录类型: phone, account, wechat-mini, wechat-official
 * @param {Object} params - 登录参数
 * @returns {Promise} 登录结果
 */
export const login = async (type, params) => {
  let url = '';
  let data = {};
  
  switch (type) {
    case 'phone':
      url = '/api/auth/login';
      data = { phone: params.phone, password: params.password };
      break;
    case 'account':
      url = '/api/auth/login';
      data = { username: params.username, password: params.password };
      break;
    case 'wechat-mini':
      url = '/api/auth/wechat-miniprogram';
      data = { code: params.code };
      break;
    case 'wechat-official':
      url = '/api/auth/wechat-official';
      data = { code: params.code };
      break;
    default:
      throw new Error('不支持的登录类型');
  }
  
  try {
    const res = await post(url, data);
    if (res.data.user && res.data.token) {
      saveUserInfo(res.data.user, res.data.token);
    }
    return res.data;
  } catch (error) {
    throw new Error(error.message || '登录失败');
  }
};

/**
 * 手机号验证码登录
 * @param {string} phone - 手机号
 * @param {string} smsCode - 验证码
 * @returns {Promise} 登录结果
 */
export const phoneSMSLogin = async (phone, smsCode) => {
  try {
    const res = await post('/api/auth/sms-login', { phone, smsCode });
    return res.data;
  } catch (error) {
    throw new Error(error.message || '验证码登录失败');
  }
};

/**
 * 获取短信验证码
 * @param {string} phone - 手机号
 * @returns {Promise} 发送结果
 */
export const getSMSCode = async (phone) => {
  try {
    const res = await post('/api/auth/sms-code', { phone });
    return res.data;
  } catch (error) {
    throw new Error(error.message || '获取验证码失败');
  }
};

/**
 * 获取公众号登录验证码
 * @returns {Promise} 验证码信息
 */
export const getWechatOfficialCode = async () => {
  try {
    const res = await post('/api/auth/wechat-official/code');
    return res.data;
  } catch (error) {
    throw new Error(error.message || '获取公众号验证码失败');
  }
};

/**
 * 检查公众号登录状态
 * @param {string} code - 公众号授权码
 * @returns {Promise} 登录状态
 */
export const checkWechatOfficialLogin = async (code) => {
  try {
    const res = await post('/api/auth/wechat-official/check', { code });
    return res.data;
  } catch (error) {
    throw new Error(error.message || '检查公众号登录状态失败');
  }
};

/**
 * 微信小程序登录
 * @param {string} code - 微信小程序登录code
 * @returns {Promise} 登录结果
 */
export const wechatMiniLogin = async (code) => {
  try {
    const res = await post('/api/auth/wechat-miniprogram', { code });
    return res.data;
  } catch (error) {
    throw new Error(error.message || '微信登录失败');
  }
};

/**
 * 微信公众号登录
 * @param {string} code - 微信公众号授权code
 * @returns {Promise} 登录结果
 */
export const wechatOfficialLogin = async (code) => {
  try {
    const res = await post('/api/auth/wechat-official', { code });
    return res.data;
  } catch (error) {
    throw new Error(error.message || '公众号登录失败');
  }
};

/**
 * 验证token有效性
 * @param {string} token - JWT token
 * @returns {Promise} 验证结果
 */
export const verifyToken = async (token) => {
  try {
    const res = await post('/api/auth/verify-token', { token });
    return res.data;
  } catch (error) {
    throw new Error(error.message || 'token验证失败');
  }
};

/**
 * 获取腾讯云IM配置
 * @returns {Promise} 配置信息
 */
export const getIMConfig = async () => {
  try {
    const res = await get('/api/auth/config');
    return res.data;
  } catch (error) {
    throw new Error(error.message || '获取配置失败');
  }
};

/**
 * 生成腾讯云IM用户签名
 * @param {string} userId - 用户ID
 * @param {number} expire - 签名有效期（秒）
 * @returns {Promise} 签名信息
 */
export const generateUserSig = async (userId, expire = 15552000) => {
  try {
    const res = await post('/api/auth/generate-usersig', { userId, expire });
    return res.data;
  } catch (error) {
    throw new Error(error.message || '生成签名失败');
  }
};

/**
 * 保存用户信息到本地存储
 * @param {Object} userInfo - 用户信息
 * @param {string} token - JWT token
 */
export const saveUserInfo = (userInfo, token) => {
  try {
    storage.set('userInfo', userInfo);
    storage.set('token', token);
    return true;
  } catch (error) {
    console.error('保存用户信息失败:', error);
    return false;
  }
};

/**
 * 获取本地存储的用户信息
 * @returns {Object} 用户信息
 */
export const getUserInfo = () => {
  try {
    return storage.get('userInfo') || null;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

/**
 * 获取本地存储的token
 * @returns {string} token
 */
export const getToken = () => {
  try {
    return storage.get('token') || '';
  } catch (error) {
    console.error('获取token失败:', error);
    return '';
  }
};

/**
 * 清除本地存储的用户信息
 */
export const clearUserInfo = () => {
  try {
    storage.remove('userInfo');
    storage.remove('token');
    return true;
  } catch (error) {
    console.error('清除用户信息失败:', error);
    return false;
  }
};

/**
 * 检查用户是否已登录
 * @returns {boolean} 是否已登录
 */
export const isLoggedIn = () => {
  const token = getToken();
  const userInfo = getUserInfo();
  return !!(token && userInfo);
};
